export default function exportExcel(tableThs, tableData, tableName) {
  const levelThsArr = [] //分层th
  const thsArr = [] //数据用col
  let rowNum = 0 //最多几行tr

  function pushTh(th, level = 1) {
    th.level = level
    if (rowNum < level) rowNum = level
    levelThsArr[level - 1] ??= []
    levelThsArr[level - 1].push(th)
    if (!th.children) thsArr.push(th)
    else {
      th.children.forEach((t) => {
        t.parentTh = th
        pushTh(t, level + 1)
      })
    }
  }

  function setRowspan(th, count) {
    if (!th.children) th.rowspan = count
    else {
      th.rowspan = 1
      th.children.forEach((t) => {
        setRowspan(t, count - 1)
      })
    }
  }

  function setColspan(th) {
    if (!th.children) {
      th.colspan = 1
    } else {
      th.colspan = th.children.reduce((pre, val) => (pre += val.colspan), 0)
    }
    if (th.parentTh) setColspan(th.parentTh)
  }

  tableThs.forEach((th) => pushTh(th))

  tableThs.forEach((th) => setRowspan(th, rowNum))

  thsArr.forEach((th) => setColspan(th))

  const domStr = `
    <table border="1">
      ${levelThsArr.reduce((pre, cur) => {
        return (pre += `
          <tr>
              ${cur.reduce((p, c) => {
                return (p += `<td colspan=${c.colspan ?? 1} rowspan=${c.rowspan ?? 1}>${
                  c.title
                }</td>`)
              }, '')}
          </tr>`)
      }, '')}
      ${tableData.reduce((pre, cur) => {
        return (pre += `
          <tr>
              ${thsArr.reduce((p, c) => {
                return (p += `<td style="mso-number-format:'\@';width: 100px">${
                  cur[c.dataIndex]
                }</td>`)
              }, '')}
          </tr>`)
      }, '')}
    </table>`
  const excelFile = `
    <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>
      <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
      <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
      <head>
      <!--[if gte mso 9]>
      <xml>
        <x:ExcelWorkbook>
          <x:ExcelWorksheets>
            <x:ExcelWorksheet>
              <x:Name>
                sheet
              </x:Name>
            <x:WorksheetOptions>
              <x:DisplayGridlines/>
            </x:WorksheetOptions>
            </x:ExcelWorksheet>
          </x:ExcelWorksheets>
        </x:ExcelWorkbook>
      </xml>
      <![endif]-->
      </head>
      <body>
        ${domStr}
      </body>
    </html>`.trim()
  const blob = new Blob([excelFile], { type: 'application/vnd.ms-excel' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.style.visibility = 'hidden'
  link.download = (tableName ?? '未命名') + '.xls'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
